/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vesko1.model;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Nikolay
 */
public class CarDAO {

    public static Car findByRegNumber(String regNumber) {
        Car car = null;
        try {
            Connection con = DBConnection.getCon();
            Statement stmt = con.createStatement();
            ResultSet set = stmt.executeQuery("SELECT * FROM car WHERE regnumber = '" + regNumber + "';");

            if (set.next()) {
                Person driver = PersonDAO.findByEgn(set.getString("driver_id"));
                Person owner = PersonDAO.findByEgn(set.getString("owner_id"));

                car = new Car(set.getString(1), set.getString(2), set.getString(3), set.getString(4), set.getFloat(5),
                        set.getFloat(6), set.getInt(7), set.getInt(8), driver, owner);
            }
        } catch (Exception e) {
            System.out.println("Cannot find car with number : " + regNumber);
        }

        return car;
    }

    public static void addNewCar(Car c) {
        try {
            if (findByRegNumber(c.getRegNumber()) == null) {
                Connection con = DBConnection.getCon();
                Statement stmt = con.createStatement();

                stmt.executeUpdate("INSERT INTO car values "
                        + "('" + c.getRegNumber() + "', '" + c.getRama() + "','" + c.getMarka()
                        + "','" + c.getModel() + "'," + c.getCubics()
                        + "," + c.getTonnage() + "," + c.getSeats() + "," + c.getYearOfMade()
                        + ",'" + c.getDriver().getEgn() + "','" + c.getOwner().getEgn() + "'); ");


                System.out.println("1 new car inserted!");
            }

        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}
